package com.easy.easy.Controller;

import com.easy.easy.Service.IOrderinfoService;
import com.easy.easy.bean.Order;
import com.easy.easy.bean.Orderinfo;
import com.easy.easy.bean.User;
import com.easy.easy.util.LayData;
import com.easy.easy.util.Page;
import com.easy.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("orderinfo")
public class OrderinfoController {
    @Autowired
    IOrderinfoService orderinfoService;

    @RequestMapping("getorderinfobyid")
    @ResponseBody
    public LayData getorderbyid(int orderid) {

        Orderinfo orderinfo = orderinfoService.getOrderById(orderid);
        return new LayData(0,"",1,orderinfo);
    }

    @RequestMapping("add")
    @ResponseBody
    public int add(Orderinfo orderinfo) {
        return orderinfoService.add(orderinfo);
    }

    @RequestMapping("getorderinfobyuserid")
    @ResponseBody
    public LayData getorderinfobyuserid(HttpSession session) {
        // 从会话中获取当前登录的用户
        User user = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);

        // 检查用户是否登录
        if (user == null) {
            return new LayData(1, "用户未登录", 0, null);
        }

        // 调用服务层方法获取订单信息
        Orderinfo orderinfo = orderinfoService.getOrderinfoByUserId(user.getUserid());

        // 检查是否成功获取到订单信息
        if (orderinfo == null) {
            return new LayData(1, "未找到订单信息", 0, null);
        }

        // 返回成功的响应，包含订单信息
        return new LayData(0, "获取成功", 1, orderinfo);
    }



    @RequestMapping("list")
    @ResponseBody
    public LayData getList(Page page, String text, HttpSession session) {

        User user = (User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);

        // 检查用户是否登录
        if (user == null) {
            return new LayData(1, "用户未登录", 0, null);
        }

        // 确保page对象不为null，并且有合理的默认值
        if (page == null) {
            page = new Page();
            page.setLimit(10); // 设置默认每页显示10条
        }

        System.out.println("分页参数: start=" + page.getStart() + ", limit=" + page.getLimit());

        List<Orderinfo> list = orderinfoService.getList(page, text, user.getUserid());
        int count = orderinfoService.getCount(text, user.getUserid());
        System.out.println("user的值为"+user.getUserid());
        System.out.println("查询到订单数量: " + count);
        System.out.println("返回订单列表大小: " + (list != null ? list.size() : 0));

        return new LayData(0, "获取成功", count, list);
    }
}
